<?php

namespace app\admin\service;

use app\model\Banner;
use app\model\Videos;
use app\common\Error;
use think\facade\Cache;

class BannerService
{
    private $model;
    private $videosModel;

    public function __construct(Banner $model, Videos $videosModel)
    {
        $this->model = $model;
        $this->videosModel = $videosModel;
    }

    // 获取banner列表
    public function getBannerList($params)
    {
        $data = $this->model->getList('id, video_id, cover_img, path', 'sort desc');

        $videoIds = array_column($data, 'video_id');
        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
        $videoResult = array_column($videoData, 'name', 'id');

        foreach ($data as $key => $item) {
            $data[$key]['video_name'] = empty($videoResult[$item['video_id']]) ? '' : $videoResult[$item['video_id']];
        }

        return $data;
    }

    // 获取banner详情
    public function getBannerDetail(int $id)
    {
        $data = $this->model->getInfoById($id, 'id, video_id, cover_img, path, sort, activity_id, type');
        return $data;
    }

    // 添加/编辑banner
    public function editBanner($params)
    {
        if (empty($params['id'])) {

            $data = $this->model->getDataByWhere(['video_id' => $params['video_id']]);
            if ($data) {
                return ['message' => Error::CANNOT_ADD_REPEATEDLY];
            }

            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        if (empty($params['cover_img']) && !empty($params['video_id'])) {
            $videoData = $this->videosModel->getInfoById($params['video_id'], 'cover_img');
            $params['cover_img'] = $videoData['cover_img'];
        }else {
            $ossAccessAddress = config('filesystem.alioss.oss_access_address');
            if (strpos($params['cover_img'], $ossAccessAddress['original_access_address']) !== false) {
                $params['cover_img'] = str_replace($ossAccessAddress['original_access_address'], $ossAccessAddress['cdn_accelerated_domain'], $params['cover_img']);
            }
        }

        $id = $this->model->edit($params);

        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.banner_diagram_key');
        $redis->select(7);
        $redis->del($key);
        if (!$id) {
            return false;
        }

        return true;
    }

    // 删除banner
    public function deleteBanner(int $id)
    {
        $bool = $this->model->destroy($id);

        if (!$bool) {
            return false;
        }
        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.banner_diagram_key');
        $redis->select(7);
        $redis->del($key);
        return true;
    }
}